/**
 * 
 */
package pt.mleiria.bean;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashSet;
import java.util.Set;

import javax.crypto.KeyGenerator;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import pt.mleiria.entity.DerivedKeys;
import pt.mleiria.entity.IssuerMasterKey;

/**
 * @author NB13712
 *
 */
@Stateless
public class ClientBean implements IClientBean{
private static final Logger LOG = Logger.getLogger(ClientBean.class);
	
	@PersistenceContext(unitName = "pu1")
	private EntityManager em;
	
	/**
	 * 
	 */
	public ClientBean() {
	
	}
	
	public String insertMasterKey(final String name) throws NoSuchAlgorithmException {

		final IssuerMasterKey imk0 = new IssuerMasterKey();
        //imk0.setId(id);
        imk0.setName(name);
        final KeyGenerator generator = KeyGenerator.getInstance("DES");
        generator.init(new SecureRandom());
        final Key key = generator.generateKey();
        final byte[] cryptoKey = key.getEncoded();
        LOG.info("Key length="+ cryptoKey.length);
        final DerivedKeys dk = new DerivedKeys();
        dk.setCryptoKey(cryptoKey);
        //dk.setId(1);
        dk.setIssuerMasterKey(imk0);
        Set<DerivedKeys> dKeys = new HashSet<DerivedKeys>();
        dKeys.add(dk);
        imk0.setDkeys(dKeys);
        em.persist(imk0);
        return "OK";
    }
	
	public byte[] getKey(final String name, final int key_id){
		final IssuerMasterKey imk = findIssuerMasterKey(name);
		final Set<DerivedKeys> dkSet = imk.getDkeys();
		for(DerivedKeys dk : dkSet){
			if(dk.getId() == key_id){
				return dk.getCryptoKey();
			}
		}
		return null;
	}
	
	/*
    private String verifyInsert() {

        IssuerMasterKey c = findIssuerMasterKey("99999");

        Set<DerivedKeys> dkeys = c.getDkeys();
        if (dkeys == null || dkeys.size() != 2) {
            throw new RuntimeException("Unexpected number of orders: " 
                    + ((dkeys == null)? "null" : "" + dkeys.size()));
        }
        
        Iterator<DerivedKeys> it = dkeys.iterator(); 
        while(it.hasNext()){
        	
        	LOG.info(it.next());
        }
        return "OK";
    }

    private String testDelete(IssuerMasterKey c) {

        // Merge the customer to the new persistence context
        IssuerMasterKey c0 = em.merge(c);

        // Delete all records.
        em.remove(c0);

        return "OK";
    }

    private String verifyDelete() {

        Query q = em.createQuery("select c from IssuerMasterKey c");
        List results = q.getResultList();

        if (results == null || results.size() != 0) {
            throw new RuntimeException("Unexpected number of customers after delete");
        }

        q = em.createQuery("select o from DerivedKeys o");
        results = q.getResultList();

        if (results == null || results.size() != 0) {
            throw new RuntimeException("Unexpected number of orders after delete");
        }

        return "OK";
    }
*/
    public IssuerMasterKey findIssuerMasterKey(String name) {
    	LOG.info("findIssuerMasterKey: name=" + name);
        Query q = em.createQuery("select c from IssuerMasterKey c where c.name = :name");
        q.setParameter("name", name);
        return (IssuerMasterKey)q.getSingleResult();

    }
    public IssuerMasterKey findIssuerMasterKey(int id) {
    	LOG.info("findIssuerMasterKey: id=" + id);
        Query q = em.createQuery("select c from IssuerMasterKey c where c.id = :id");
        q.setParameter("id", id);
        return (IssuerMasterKey)q.getSingleResult();

    }
}
